<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发布订阅网上</title>
</head>

<body>
    <script>
        const Publisher = (function () {
            // 存储订阅者
            const _subsMap = {};
            return {
                // 消息订阅
                subscribe(type, cb) {
                    if (_subsMap[type]) {
                        if (!_subsMap[type].includes(cb)) {
                            // 注册一个函数
                            _subsMap[type].push(cb)
                        }
                    } else {
                        // 初始化一个数组
                        _subsMap[type] = [cb]
                    }
                },
                // 消息退订
                unsubscribe(type, cb) {
                    if (!_subsMap[type] || !_subsMap[type].includes(cb)) {
                        return
                    }
                    const idx = _subsMap[type].indexOf(cb)
                    _subsMap[type].splice(idx, 1)
                },
                // 消息发布
                notify(type, ...payload) {
                    if (!_subsMap[type]) {
                        return
                    };
                    _subsMap[type].forEach(cb => cb(...payload))
                }
            }
        })()



        // 订阅运动鞋
        Publisher.subscribe('运动鞋', message => console.log('15224334XXX' + message));
        Publisher.subscribe('运动鞋', message => console.log('13823344XXX' + message));
        // 订阅帆布鞋
        Publisher.subscribe('帆布鞋', message => console.log('13924323XXX' + message));
        console.log(Publisher._subsMap);

        // 打电话通知买家运动鞋消息
        Publisher.notify('运动鞋', ' 运动鞋到货了');
        // 15224334XXX 运动鞋到货了 
        // 13823344XXX 运动鞋到货了

        // 打电话通知买家帆布鞋消息  
        Publisher.notify('帆布鞋', ' 帆布鞋售罄了');
// 13924323XXX 帆布鞋售罄了
    </script>
</body>

</html>